#include "loginwindow.h"
#include <registerwindow.h>
#include <forgotpassworddialog.h>
#include "MainWindow.h"
#include <QMessageBox>
#include <QSettings>
#include <QHBoxLayout>
#include <QDebug>
#include <QFile>
#include <QApplication>

LoginWindow::LoginWindow(QWidget *parent)
    : QDialog(parent)
    , lineEditUserName(new QLineEdit(this))
    , lineEditPassword(new QLineEdit(this))
    , buttonLogin(new QPushButton("登录", this))
    , labelTitle(new QLabel("登录器", this))
    , checkBoxRemember(new QCheckBox("记住密码", this))
    , buttonTogglePassword(new QPushButton("👁", this))
    , lockTimer(new QTimer(this))
    , buttonRegister(new QPushButton("注册",this))
    , comboBoxUserList(new QComboBox(this))
    , buttonCheck(new QPushButton("查看Settings",this))
    , buttonClear(new QPushButton("删除子组",this))
    , buttonRetrieve(new QPushButton("找回密码",this))
    ,failedAttempt(0)
{
    QFile file("D:\\qt-projects\\Loginer\\style.qss.txt"); // 使用资源路径
    labelTitle->setObjectName("labelTitle");
    buttonLogin->setObjectName("buttonLogin");
    buttonRegister->setObjectName("buttonRegister");
    buttonCheck->setObjectName("buttonCheck");
    buttonClear->setObjectName("buttonClear");
    buttonTogglePassword->setObjectName("buttonTogglePassword");
    checkBoxRemember->setObjectName("checkBoxRemember");

    buttonRetrieve->setFlat(true);

    if (file.open(QFile::ReadOnly)) {
        QTextStream stream(&file);
        QString style = stream.readAll();
        qApp->setStyleSheet(style);  // 将样式应用到整个应用
    }

    setupUI();
    loadSettings();
    loadUserList();
}


LoginWindow::~LoginWindow(){}

void LoginWindow::setupUI(){
    setWindowTitle("登录界面");
    resize(400,300);
    lineEditUserName->setFixedWidth(327);
    comboBoxUserList->setEditable(false);

    labelTitle->setAlignment(Qt::AlignCenter);
    labelTitle->setStyleSheet("font-size: 24px; font-weight:bold;");

    lineEditUserName->setPlaceholderText("请输入用户名！");
    lineEditPassword->setPlaceholderText("请输入密码！");
    lineEditPassword->setEchoMode(QLineEdit::Password);

    QHBoxLayout *passwordLayout =new QHBoxLayout();
    QHBoxLayout *rememberRetrieveLayout=new QHBoxLayout();
    passwordLayout->addWidget(lineEditPassword);
    passwordLayout->addWidget(buttonTogglePassword);
    buttonTogglePassword->setFixedWidth(40);
    buttonRetrieve->setFixedWidth(70);

    QVBoxLayout *mainLayout=new QVBoxLayout();
    mainLayout->addWidget(labelTitle);
    mainLayout->addSpacing(20);
    mainLayout->insertWidget(2,comboBoxUserList);
    mainLayout->addWidget(lineEditUserName);
    mainLayout->addLayout(passwordLayout);
    rememberRetrieveLayout->addWidget(checkBoxRemember);
    rememberRetrieveLayout->addWidget(buttonRetrieve);
    mainLayout->addLayout(rememberRetrieveLayout);
    mainLayout->addWidget(buttonLogin);
    mainLayout->addWidget(buttonRegister);
    mainLayout->addWidget(buttonCheck);
    mainLayout->addWidget(buttonClear);
    setLayout(mainLayout);

    connect(buttonLogin,&QPushButton::clicked,this,&LoginWindow::handleLogin);
    connect(buttonTogglePassword,&QPushButton::clicked,this,[=](){
        if(lineEditPassword->echoMode()==QLineEdit::Password){
            lineEditPassword->setEchoMode(QLineEdit::Normal);
            buttonTogglePassword->setText("🙈");
        }else{
            lineEditPassword->setEchoMode(QLineEdit::Password);
            buttonTogglePassword->setText("👁");
        }
    });

    connect(lockTimer,&QTimer::timeout,this,[=](){
        buttonLogin->setEnabled(true);
        lockTimer->stop();
        failedAttempt=0;
    });

    connect(buttonRegister,&QPushButton::clicked,this,[=](){
        RegisterWindow *registerWindow=new RegisterWindow(this);
        registerWindow->exec();
    });

    connect(lineEditUserName,&QLineEdit::textChanged,this,[=](){
        lineEditPassword->clear();
        checkBoxRemember->setChecked(false);
    });

    connect(buttonCheck, &QPushButton::clicked, this, [=]() {
        QSettings settings("MyApp", "LoginDemo");
        QStringList groups = settings.childGroups();
        qDebug() << "Top-level groups in settings:" << groups;

        for (const QString &group : groups) {
            settings.beginGroup(group);
            if (group == "user") {
                QStringList subGroups = settings.childGroups();
                qDebug() << "Subgroups in user:" << subGroups;

                for (const QString &subGroup : subGroups) {
                    settings.beginGroup(subGroup);
                    QStringList keys = settings.childKeys();
                    qDebug() << "User:" << subGroup;
                    for (const QString &key : keys) {
                        qDebug() << " Key:" << key << ", Value:" << settings.value(key).toString();
                    }
                    settings.endGroup();
                }
            } else {
                QStringList keys = settings.childKeys();
                qDebug() << "Group:" << group;
                for (const QString &key : keys) {
                    qDebug() << " Key:" << key << ", Value:" << settings.value(key).toString();
                }
            }
            settings.endGroup();
        }
    });



    connect(buttonClear,&QPushButton::clicked,this,[=](){
        QSettings settings("MyApp", "LoginDemo");

        // 进入 user 分组
        settings.beginGroup("user");

        // 获取所有子分组（用户）
        QStringList userGroups = settings.childGroups();

        // 遍历并删除每个子分组
        for (const QString &user : userGroups) {
            if(user=="zzz"){
                settings.remove(user);
            }
        }

        // 离开 user 分组
        settings.endGroup();

        qDebug() << "User table cleared!";
    });

    connect(buttonRetrieve, &QPushButton::clicked, this, []() {
        ForgotPasswordDialog *dialog = new ForgotPasswordDialog();
        dialog->exec();
    });


    connect(comboBoxUserList,&QComboBox::currentTextChanged,this,&LoginWindow::loadSettingsForUser);
}

void LoginWindow::handleLogin() {
    QString username = lineEditUserName->text();
    QString password = lineEditPassword->text();

    if (username.isEmpty() || password.isEmpty()) {
        QMessageBox::warning(this, "登录失败", "用户名和密码不能为空！");
        return;
    }

    QSettings settings("MyApp", "LoginDemo");

    if (username == "admin" && password == "123456") {
        failedAttempt = 0;
        saveSettings(username, password, checkBoxRemember->isChecked());

        MainWindow *mainwindow = new MainWindow();
        mainwindow->show();
        this->close();
        return;
    }

    settings.beginGroup("user");
    if (settings.childGroups().contains(username)) { // 检查用户是否存在
        settings.beginGroup(username);
        QString storedPassword = settings.value("password").toString();
        settings.endGroup();

        if (storedPassword == password) { // 密码验证
            failedAttempt = 0;
            saveSettings(username, password, checkBoxRemember->isChecked());

            MainWindow *mainwindow = new MainWindow();
            mainwindow->show();
            this->close();
        } else {
            failedAttempt++;
            QMessageBox::critical(this, "登录失败", "用户名或密码错误！");
        }
    } else {
        failedAttempt++;
        QMessageBox::critical(this, "登录失败", "用户名或密码错误！");
    }
    settings.endGroup();

    if (failedAttempt >= 3) {
        QMessageBox::critical(this, "登录失败", "尝试次数过多，请稍后再登录！");
        buttonLogin->setEnabled(false);
        lockTimer->start(10000);
    }
}


void LoginWindow::loadSettings(){
    QSettings settings("MyApp","LoginDemo");
    QString username=settings.value("username").toString();
    QString password=settings.value("password").toString();

    lineEditUserName->setText(username);
    lineEditPassword->setText(password);

    if(!username.isEmpty()&&!password.isEmpty()){
        checkBoxRemember->setChecked(true);
    }
}

void LoginWindow::saveSettings(const QString &username, const QString &password, bool checkRemember){
    QSettings settings("MyApp", "LoginDemo");
    settings.setValue("lastUser", username);

    if(username=="admin"){
        settings.beginGroup(username);
        settings.setValue("remember", checkRemember);
        settings.endGroup();
    }else{
        settings.beginGroup("user");
        settings.beginGroup(username);
        settings.setValue("remember", checkRemember);
        settings.endGroup();
        settings.endGroup();
    }


    comboBoxUserList->addItem(username);


}

void LoginWindow::loadUserList() {
    QSettings settings("MyApp", "LoginDemo");
    comboBoxUserList->clear();

    QString lastUser = settings.value("lastUser").toString();
    loadSettingsForUser(lastUser);
    comboBoxUserList->addItem(lastUser);

    settings.beginGroup("user");
    for (const QString &group : settings.childGroups()) {
        if(group!=lastUser){
            comboBoxUserList->addItem(group);
        }
    }
    settings.endGroup();
    if(lastUser!="admin"){
        comboBoxUserList->addItem("admin");
    }
}


void LoginWindow::loadSettingsForUser(const QString &username){
    QSettings settings("MyApp","LoginDemo");
    if(username!="admin"){
        settings.beginGroup("user");
    }
    settings.beginGroup(username);

    QString password=settings.value("password").toString();
    bool remember=settings.value("remember").toBool();

    if(username!="admin"){
        settings.endGroup();
    }
    settings.endGroup();

    lineEditUserName->setText(username);
    if(remember){
        lineEditPassword->setText(password);
        checkBoxRemember->setChecked(true);
    }else{
        lineEditPassword->clear();
        checkBoxRemember->setChecked(false);
    }
}

